


//package jp.tuyano;

import ikelib.MyDirectory;
import ikelib.menuUtil;
import ikelib.wintime;

import java.awt.*;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.*;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.FileChannel;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.net.ssl.HttpsURLConnection;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.LookAndFeel;
import javax.swing.OverlayLayout;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.filechooser.FileNameExtensionFilter;

import checkerView.CheckerView;

import GraphicView.GraphicView;
import GraphicView.GraphicViewPanel;

import dynamicrange.DynamicRangePanel;
import dynamicrange.DynamicRangeView;

import signalprocessing.SignalProcessingPanel;
import spectrum.SpectrumView;
import spectrum.SpectrumViewPanel;

import wcg.ChannelDataCollection;
import wcg.DialogIrigInfo;
import wcg.DlgReceiveUDPSetting;
import wcg.DlgSelectRecentFile;
import wcg.DlgSystemOption;
import wcg.JComboBoxInOptionpane;
import wcg.KNET_ascii;
import wcg.OptioncommandInterface;
import wcg.Optionconsole;
import wcg.OutputTextArea;
import wcg.PDFViewAndPrint;
import wcg.RemoteUpdate;
import wcg.UdpCallBack;
import wcg.WinReceiver;
import wcg.helpWindow;
import wcg.winDataBase;
import wcg.winDataBaseChange;
import wcg.winUdp2File;
import wcg.winchkOption;
import wcg.winchkgProperty;

/**
 * WinChkg is a tool to check the WIN format.
 * This class is the main frame of the application. 
 * 	
 * @author ikechan
 * 
 *
 */
public class winchkg extends JFrame implements ActionListener ,UdpCallBack, ItemListener 
												,ChangeListener,OptioncommandInterface,MenuListener  {
	/**
	 * 
	 */
	//public static final String Version = "2.0.8";
	public static final String Version = "3.1.7";
	private static String Edition = "Lite";
	private static final String Company = "HAKUSAN Corp.";
	
	private static String Title = "winchkg ver" + Version + " " + Edition + "  / " + Company;

	//private static final String RemoteFolder ="file:\\\\192.168.110.12\\白山データ\\部門別\\通信システム事業部\\開発Gr\\ツール\\winデータビューア winchkg\\";
	// private static final String RemoteFolder = 	"file:\\\\LANDISK2\\share\\";
	private static final String RemoteFolder = "http://www.hakusan.co.jp/download/keisoku/update/tool/viewer/winchkg/";
	private static final String RemotePost = "http://www.hakusan.co.jp/h-cms/mc/log.php";
	
	private  TreeMap JavaPropertyMap = null;	// Java#System#getPropertyで得られるプロパティ
	private int WinchkgID1 = 0;	// ユーザディレクトリ名、ユーザ名などから定まる一意の32bit値 
	private int WinchkgID2 = 0;	// インストールディレクトリから定まる一意の32bit値 
	private String WinchkgID = null; // winchkgID1,winchkgID2の文字列表現 xxxx-yyyy (winchgID1-winchkgID2 hex)
	private String MyPath = null; //  winchkgのインストールパス
	
	private String WinchkglnchVersion = null;	 // winchkglnchのバージョン
	private static final String RemoteVersionFile = "version.txt";
	private String MyJarFile = "winchkg.jar";
	
	private static final String UpdateBetaVersionKey = "winchkgbeta";
	private static final String UpdateDistribeVersionKey = "winchkg";
	private static String UpdateVersionKey = UpdateDistribeVersionKey;
	
//	private static final String UpdateNewVersionFile = "winchkg-new.jar";
	private static final String UpdateLauncher = "winchkglnch.jar";
//	private static final String UpdateLauncherVersionFile = "winchkglnch.ini";
	static final String WinchkglnchKey = "winchkglnch";
	static final String WinchkglnchIniFile = "winchkglnch.ini";	
	
	private DialogIrigInfo DlgIrigInfo = null;
	private int RetryCounter=0;
	private int RetryRecvCounter=0;
	private int Durty=0;
	private LinkedList<byte[]> UdpList = new LinkedList<byte[]>();
	private winUdp2File WinUdp2File = new winUdp2File();

	private static final String PropertyFile = "winchkg.ini";
	
	private int		Port = 7202;
	private WinReceiver WinServer = null;
	private boolean RxEnable = false;
	private int FileWriteEnable = 0;

	private static final long serialVersionUID = 1L;
	private 	PanelTopView TopTabbedView;

	private int DisplayLevel = 1;
	private int DispCounter=0;
	private JCheckBoxMenuItem DisableSendAck=null;

	
	private JMenuBar MyMenuBar 	= null;
	
	
	private Optionconsole console = null;
	public winchkgProperty  Prop = new winchkgProperty(PropertyFile);
	private String currentFileOpenDirectory=null;
	
	private MyDirectory.OSName OsName =MyDirectory.OSName.WINDOWS;
	

	/**
	 * プログラムのタイトルバー
	 * @return
	 */
	private String makeProgramTitle(){
		 String ret = new String("winchkg ver" + Version + " " +  winchkgProperty.getEditionNames() + "  / " + Company);
		 return  ret;
	}
	/**
	 *  main routine of the application
	 * @param args 
	 *  no use 
	 */
//	private static String WinchkgLAFFile = "winchkglaf.ini";
	public static void main(String[] args) {
		winchkg WinchkG = new winchkg();
		WinchkG.run(args);
	}
	/**
	 */
	
	/**
	 * プロパティのロードとセーブ
	 * @param save
	 */
	private void LoadSaveProperty(boolean save){

		if(save){
			String str = TopTabbedView.DataBase.getWriteOutFolder();
			winchkgProperty.WriteFileFolder = new String(str);
			
			try{
				Port = Integer.valueOf(getGraphicViewPanel().jTextFieldPort.getText());
			} catch(NumberFormatException e){
				e.printStackTrace();
			}
			winchkgProperty.Port = Port;
			Dimension dm = this.getSize();
			winchkgProperty.WindowSizeX = dm.width;
			winchkgProperty.WindowSizeY = dm.height;
			Point pt = this.getLocationOnScreen();
			winchkgProperty.WindowPosX = pt.x;
			winchkgProperty.WindowPosY = pt.y;
			getGraphicView().LoadSaveProperty(save);
			TopTabbedView.DataBase.LoadSaveProperty(save);
			if(TopTabbedView.Checker != null){
				TopTabbedView.Checker.LoadSaveProperty(save,Prop);
			}
			SpectrumView sp = getSpectrumView();
			if(sp!=null) sp.LoadSaveProperty(save);
			
			DynamicRangeView sn = getSNRView();
			if(sn!=null) sn.LoadSaveProperty(save);
			
			if(TopTabbedView.SignalProcessing != null){
				TopTabbedView.SignalProcessing.LoadSaveProperty(save);;
			}
		}
		else{
			Prop.LoadSaveProperty(save);
			getGraphicView().LoadSaveProperty(save);
			TopTabbedView.DataBase.LoadSaveProperty(save);
			if(TopTabbedView.Checker != null){
				TopTabbedView.Checker.LoadSaveProperty(save,Prop);
			}
			SpectrumView sp = getSpectrumView();
			if(sp!=null) sp.LoadSaveProperty(save);

			DynamicRangeView sn = getSNRView();
			if(sn!=null) sn.LoadSaveProperty(save);
			
			if(TopTabbedView.SignalProcessing != null){
				TopTabbedView.SignalProcessing.LoadSaveProperty(save);;
			}
			
			Port = winchkgProperty.Port;
		}
	}
	
	/**
	 * 
	 * @param arg
	 */
	public void run(String[] arg){
		//--------------------------------------------------------
		//　トップのタブビュー
		TopTabbedView = new PanelTopView();
		TopTabbedView.GraphPanel.setParent(this);
		TopTabbedView.GraphPanel.setProperty(Prop);
		
		this.add(TopTabbedView,BorderLayout.CENTER);
		
		
		TopTabbedView.addChangeListener(new ChangeListener (){
			public void  stateChanged(ChangeEvent e){
				onTabChanged();
			}
		});
		//--------------------------------------------------------
		//　プロパティーファイルの読み出し
		//WinChkgProperty.Load();
		LoadSaveProperty(false); // loading
		
	    //--------------------------------------------------------
	    // 自分のパスを保存
		MyDirectory mydir = new MyDirectory();
		File my = mydir.getDirectory();
		MyPath = my.getAbsolutePath();
		OsName = mydir.getOsName();
		WinchkgID2 = MyPath.hashCode();
		//--------------------------------------------------------
		// JAVA System property の取得
	    try{
			Properties p = System.getProperties();
		    JavaPropertyMap = new TreeMap();
		    JavaPropertyMap.putAll(p);
		    String osname   = (String)JavaPropertyMap.get("os.name");
		    String username = (String)JavaPropertyMap.get("user.name");
		    String userhome = (String)JavaPropertyMap.get("user.home");
		    WinchkgID1 = osname.hashCode() ^ username.hashCode() ^ userhome.hashCode();
	    }
	    catch(SecurityException e){
	    	e.printStackTrace();
	    }
		WinchkgID = Integer.toHexString(WinchkgID1).toUpperCase()+"-"+Integer.toHexString(WinchkgID2).toUpperCase(); 

		//--------------------------------------------------------		
		
		//this.setLocationByPlatform(true);
		//--------------------------------------------------------
		//--------------------------------------------------------
		// メニュー
		setMenuBar();
		
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		if(winchkgProperty.WindowSizeX<100 || winchkgProperty.WindowSizeY<100 || winchkgProperty.WindowPosX<0 || winchkgProperty.WindowPosY < 0
				|| winchkgProperty.WindowPosX>d.width-20 || winchkgProperty.WindowPosY> d.height-20){
			winchkgProperty.WindowSizeX=700;
			winchkgProperty.WindowSizeY=600;
			winchkgProperty.WindowPosX = 0;
			winchkgProperty.WindowPosY = 0;
		}
		this.setSize(winchkgProperty.WindowSizeX,winchkgProperty.WindowSizeY);
		this.setLocation(winchkgProperty.WindowPosX, winchkgProperty.WindowPosY);
		WinUdp2File.setPath(winchkgProperty.WriteFileFolder);
		
		TopTabbedView.DataBase.setWriteOutFolder(winchkgProperty.WriteFileFolder);
		TopTabbedView.GraphPanel.jTextFieldPort.setText(String.format("%d",Port));
		TopTabbedView.GraphPanel.jTextFieldWriteFileDir.setText(WinUdp2File.getPath());
		TopTabbedView.DataBase.setWriteOutFolder(WinUdp2File.getPath());

		
//		if(winchkgPropInst.EditionControl == winchkgPropInst.EditionControlFull){
//			Edition = "Developers";
			setTitle(makeProgramTitle());
//		}
		this.setVisible(true);

		if(winchkgProperty.UpdateBeta){
			UpdateVersionKey = UpdateBetaVersionKey;
		}
		else{
			UpdateVersionKey = UpdateDistribeVersionKey;
		}
		
		Timer t = new Timer();
		t.schedule(new cTimer(),0,100);

		wintime wt = new wintime();
		//--------------------------------------------------------
		
		addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent ev){
				onExit();
			}

		});
		//-------------------------------------------------------------
		// データが変化したとき
		TopTabbedView.DataBase.addChangeListener(new winDataBaseChange(){
			public void OnChangeDataBase(int hint,int ch,ChannelDataCollection dcol){
				switch(hint){
				case winDataBaseChange.EVENT_CHANNEL_CLEAR:
				case winDataBaseChange.EVENT_CHANNEL_ADD:
				case winDataBaseChange.EVENT_CHANNEL_REMOVE:
				case winDataBaseChange.EVENT_DATA_CLEAR:
				case winDataBaseChange.EVENT_DATA_REMOVE:
				case winDataBaseChange.EVENT_DATA_PUT:
					break;
				case winDataBaseChange.EVENT_SAVE_FOLDER_CHANGE:
					WinUdp2File.setPath(TopTabbedView.DataBase.getWriteOutFolder());
					getGraphicViewPanel().jTextFieldWriteFileDir.setText(TopTabbedView.DataBase.getWriteOutFolder());
					break;
				}		
				if(TopTabbedView.SpectrumPanel != null){
					TopTabbedView.SpectrumPanel.OnChangeDataBase(hint, ch, dcol);
					
				}
				if(TopTabbedView.SNRChartPanel != null){
					TopTabbedView.SNRChartPanel.OnChangeDataBase(hint, ch, dcol);
				}
				if(TopTabbedView.SignalProcessing != null){
					TopTabbedView.SignalProcessing.OnChangeDataBase(hint, ch, dcol);
				}
			}

			@Override
			public void OnAddKNETChannelInfo(int hint, int ch, KNET_ascii knet) {
				switch(hint){
				case winDataBaseChange.EVENT_KNET_INFO_ADD:
					getGraphicView().onAddKNETasciiInfo(ch,knet);
					break;
				}
				
			}
		});

		console = new Optionconsole(null);
		console.setParent(this);
		console.setLocation(this.getLocation().x+20,this.getLocation().y+40);
		
//		for(int i=0;i<arg.length;i++){
//			System.out.println(arg[i]);
//		}
		TopTabbedView.AddFiles(arg);
		
		//onUpdate();
		if(winchkgProperty.UpdateAuto){
			long lastdate = winchkgProperty.UpdateCheckDate;
			long now      = Calendar.getInstance().getTime().getTime();
			if((now - lastdate)>1000*60*60*24){ // 24hour以上経過したらチェックする
				onUpdate(true);
				
			}
		}
		getGraphicView().setConsole(console);
		console.addParent(getGraphicView(),"ts");
	}
	//---------------------------------------------------------------------------
	// 
	public winchkg(){
		super(Title);
		Prop.LoadSaveProperty(false);
		
		//------------------ Look and feelの設定 ----------------------------------------------
		String lafname = winchkgProperty.LookAndFeel;
        UIManager.LookAndFeelInfo[] installedLafs = UIManager.getInstalledLookAndFeels();
        for(int i=0; i<installedLafs.length; i++){
            UIManager.LookAndFeelInfo info=installedLafs[i];
            if(info.getName().trim().equals(lafname)){
                try{
                    Class lnfClass = Class.forName(info.getClassName());
                    LookAndFeel laf = (LookAndFeel)(lnfClass.newInstance());
                    UIManager.setLookAndFeel(laf);
                }
                catch(Exception ex){}
            }
        }
		
		//--------------------------------------------------------
		// アプリケーションのアイコン
		URL imageIconUrl = getClass().getClassLoader().getResource("images/winchkg3-icon.png");
		ImageIcon icon = new ImageIcon(imageIconUrl);
		setIconImage(icon.getImage());
	}
	// MENU セットの補助
//	private JMenu setupMenu(String menustr,int mnemonic,String cmd){
//		JMenu ret = new JMenu(menustr);
//		if(mnemonic!=0) ret.setMnemonic(mnemonic);
//		ret.addActionListener(this);
//		ret.setActionCommand(cmd);
//		return ret;
//	}

	private JMenuItem setupMenuItem(String menustr,int mnemonic,String cmd){
		JMenuItem ret = new JMenuItem(menustr);
		if(mnemonic!=0) ret.setMnemonic(mnemonic);
		ret.addActionListener(this);
		ret.setActionCommand(cmd);
		return ret;
	}
	//--------------------------------------------------------
	// 共通のメニュー
	private void addmenuCommon(){
		
		// [ File ] ----
		JMenu menuFile = menuUtil.getMenu(MyMenuBar,"File");
		if(menuFile == null){
			menuFile = menuUtil.setupMenu("File",KeyEvent.VK_F,"File",this);
			MyMenuBar.add(menuFile,0);
		}
		menuFile.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/folder_classic.png")));
		
		
		
		JMenuItem menuOpen = setupMenuItem("Open",KeyEvent.VK_O,"Open");
		menuOpen.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/document_letter.png")));
		menuFile.add(menuOpen);

		JMenuItem menuOpenRecent = setupMenuItem("Open recent files",KeyEvent.VK_R,"OpenRecentFiles");
		menuFile.add(menuOpenRecent);

		JMenuItem menuSaveFoler = setupMenuItem("Save folder",KeyEvent.VK_D,"Save folder");
		menuSaveFoler.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/folder_classic_down.png")));
		menuFile.add(menuSaveFoler);
		
		
		
		// [Data]-[] 
		JMenu menuData = menuUtil.getMenu(MyMenuBar,"Data");
		if(menuData==null){
			menuData = menuUtil.setupMenu("Data",KeyEvent.VK_D,"Data",this);
			MyMenuBar.add(menuData,-1);
		}
		menuData.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/database_go.png")));
		
		// [Data]-[Reset Contents] 
		JMenuItem mitem = setupMenuItem("Reset Contents",KeyEvent.VK_R,"Reset Contents");
		mitem.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/trashcan.png")));
		menuData.add(mitem);
		

		// [View]-[] 
		JMenu menuView = menuUtil.getMenu(MyMenuBar,"View");
		if(menuView==null){
			menuView = menuUtil.setupMenu("View",KeyEvent.VK_V,"View",this);
			MyMenuBar.add(menuView,-1);
		}
		menuView.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/monitor.png")));

		//timeChartData.addSeparator();
		JMenuItem menuViewChanneIni = setupMenuItem("View channel.ini",0,"ViewChannelIni");
		menuViewChanneIni.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/view_ini.png")));
		menuView.add(menuViewChanneIni);

		
		// [Help]-[----] 
		JMenu menuHelp = menuUtil.getMenu(MyMenuBar,"Help");
		if(menuHelp == null){
			menuHelp = menuUtil.setupMenu("Help",KeyEvent.VK_H,"Help",this);
			MyMenuBar.add(menuHelp,-1);
		}
		menuHelp.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/help.png")));

		JMenuItem menuHelpHelp = setupMenuItem("Help-en",KeyEvent.VK_H,"Help(en)");
		menuHelpHelp.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/us.png")));
		menuHelp.add(menuHelpHelp);

		JMenuItem menuHelpHelpJ = setupMenuItem("Help-jp",KeyEvent.VK_J,"Help(jp)");
		menuHelpHelpJ.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/jp.png")));
		menuHelp.add(menuHelpHelpJ);

		JMenuItem menuUpdate = setupMenuItem("Check for updates",KeyEvent.VK_U,"Update");
		menuUpdate.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/earth.png")));
		menuHelp.add(menuUpdate);

		JMenuItem menuSystemInfo = setupMenuItem("Sytem Information",KeyEvent.VK_J,"Systeminfo");
		menuSystemInfo.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/information.png")));
		menuHelp.add(menuSystemInfo);

	
	}
	//--------------------------------------------------------
	// 共通のメニュー (後のほうに追加するメニューアイテム）
	private void addmenuCommonLast(){
		// [ File ] ----
		JMenu menuFile = menuUtil.getMenu(MyMenuBar,"File");
		if(menuFile == null){
			menuFile = menuUtil.setupMenu("File",KeyEvent.VK_F,"File",this);
			menuFile.addMenuListener(this);
			MyMenuBar.add(menuFile);
		}
		// [File]-[Receive UDP]
		menuFile.addSeparator();
		JMenuItem menuReceiveUdp = setupMenuItem("Receive UDP/File Write",KeyEvent.VK_X,"ReceiveUDP");
		menuReceiveUdp.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/server_connect.png")));
		menuFile.add(menuReceiveUdp);
		
		// [File]-[Options]
		menuFile.addSeparator();
		JMenuItem menuOptions = setupMenuItem("SystemOptions",KeyEvent.VK_O,"SystemOptions");
		menuOptions.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/sprocket_dark.png")));
		menuFile.add(menuOptions);
		
		// [File]-[Set Edition]
		if(winchkgProperty.availableEditionDialog){
			menuFile.addSeparator();
			JMenuItem menuEdition = setupMenuItem("Set Edition",KeyEvent.VK_E,"Edition");
			//menuOptions.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/sprocket_dark.png")));
			menuEdition.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent e) {
					LinkedList<String> edl = new LinkedList<String>();
					//edl.add("elementary");
					edl.add("basic");
					edl.add("users");
					String ced = winchkgProperty.getEditionNames();
					if(!edl.contains(ced)){
						edl.add(ced);
					}
					String[] ed = edl.toArray(new String[0]);
					String in = (String) JOptionPane.showInputDialog(null,"Please select edition. ( " + ced + " ) ","Edition", JOptionPane.INFORMATION_MESSAGE,null, ed,ced);
					if(in !=null){
						if(in.compareToIgnoreCase(ced)!=0){
							winchkgProperty.setEditionControl(in);
							if(JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null, "Set Edition [ "+ in + " ] \n  Re-launch now ? ","Change Edition",JOptionPane.YES_NO_OPTION)){
								reLaunchwinchkg();
							}
						}
					}
				}
				
			});
			menuFile.add(menuEdition);
		}
		
		
		// [File]-[----]
		menuFile.addSeparator();
		// [File]-[Exit]
		JMenuItem menuExit = setupMenuItem("Exit",KeyEvent.VK_X,"Exit");
		menuExit.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/exit.gif")));
		menuFile.add(menuExit);
		
		// [ Data ] ----
		JMenu menuData = menuUtil.getMenu(MyMenuBar,"Data");
		if(menuData == null){
			menuData = menuUtil.setupMenu("Data",KeyEvent.VK_D,"Data",this);
			menuData.addMenuListener(this);
			MyMenuBar.add(menuData);
		}
		menuData.addSeparator();
		JMenuItem advancedcommandconsole = setupMenuItem("Debug command console",0,"Debug command console");
		advancedcommandconsole.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/application_osx_terminal.png")));
		menuData.add(advancedcommandconsole);

		
		if(winchkgProperty.availableProtocolTest){
			menuData.addSeparator();
			DisableSendAck = new JCheckBoxMenuItem("Disable send ack (ACT)");
			menuData.add(DisableSendAck);
			DisableSendAck.addItemListener(this);
			//TimeChartData.addSeparator();
		}
	
		if(winchkgProperty.availableImportCSV){
			menuData.addSeparator();
			JMenuItem menuImport = setupMenuItem("Import CSV",0,"ImportCSV");
			menuData.add(menuImport);
		}
	
		if(winchkgProperty.availableIrigTools){
			menuData.addSeparator();
			JMenuItem irigtools = setupMenuItem("Irig tools",0,"IrigTools");
			menuData.add(irigtools);
		}	
		
		
		// [ View ] ----
		JMenu menuView = menuUtil.getMenu(MyMenuBar,"View");
		if(menuView == null){
			menuView = menuUtil.setupMenu("View",KeyEvent.VK_V,"View",this);
			menuView.addMenuListener(this);
			MyMenuBar.add(menuView);
		}
	}
	/**
	 * メニューバーをつける
	 */
	private void setMenuBar(){
		MyMenuBar = new JMenuBar();
		setJMenuBar(MyMenuBar);
		addmenuCommon();
		
		switch(TopTabbedView.getSelectedIndex()){
		case 0:
			//addmenuGraphic();
			if(TopTabbedView.GraphPanel != null){
				TopTabbedView.GraphPanel.addMenu(MyMenuBar);
			}
			break;
		case 1:
			// addmenuSpectrum(); 
			if(TopTabbedView.SpectrumPanel  != null){
				TopTabbedView.SpectrumPanel .addMenu(MyMenuBar);
			}
			break;
		case 3: 
			if(TopTabbedView.Checker  != null){
				TopTabbedView.Checker .addMenu(MyMenuBar);
			}
			
			//addmenuTools(); 
			break;
		case 2:
			//addmenuSNR();
			if(TopTabbedView.SNRChartPanel != null){
				TopTabbedView.SNRChartPanel.addMenu(MyMenuBar);
			}
			break;
		default:
		}
		addmenuCommonLast();
		
	}
	
	/**
	 * タブが変更されたとき 
	 */
	private void onTabChanged(){
		setMenuBar();
		TopTabbedView.onTabChanged();
	}
	/**
	 * win udp　サーバーをスタートさせる
	 */
	private void startWinA0Server() {
		if(WinServer != null) return;
		try{
			DatagramSocket socket = new DatagramSocket(Port);
			WinServer = new WinReceiver(socket);
			WinServer.addRecieveListener(this);
			WinServer.start();
		}catch(SocketException e) {
//			e.printStackTrace();
			JOptionPane pane = new JOptionPane(e.getMessage(),JOptionPane.INFORMATION_MESSAGE);
			JDialog dialog = pane.createDialog(this, e.getMessage());
			// モーダルの設定
			//dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
			dialog.setModalityType(Dialog.ModalityType.MODELESS );
			dialog.setVisible(true);
		}
	}
	//--------------------------------------------------------
	/**
	 * win udp サーバーをストップさせる
	 */
	private void stopWinA0Server() {
		if(WinServer != null){
			WinServer.Terminate = true;
			WinServer = null;
		}
	}
	/*
	 * System Optionの時
	 */
	private void onSystemOptions(){
		DlgSystemOption dlg = new DlgSystemOption();
		dlg.CheckUpdateOnStart = winchkgProperty.UpdateAuto;
		dlg.doDataExchange(false);
		dlg.setModal(true);
		dlg.setLocationRelativeTo(this);
		dlg.setVisible(true);
		if(dlg.RetCodeOk){
			winchkgProperty.UpdateAuto = dlg.CheckUpdateOnStart;
			winchkgProperty.LookAndFeel = dlg.LookAndFeel;
			if(dlg.LAFChange){
				if(JOptionPane.YES_OPTION != JOptionPane.showConfirmDialog(null,"Look and Feel has been changed\nRelaunch now ?","System options " ,JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE)){
					return;
				}
				reLaunchwinchkg();
			}
		}
		
	}
	//--------------------------------------------------------
	// 終了するとき
	private void onExit() {
		if(WinServer != null){
			WinServer.Terminate = true;
		}
		WinUdp2File.writeFile(true);
		//writeprop(true);
		LoadSaveProperty(true);
		Prop.LoadSaveProperty(true);// v3.16
		//Prop.Save();// v3.16
		//winChkgProperty.Save();
		System.exit(0);
	}
	//--------------------------------------------------------
	// Reset Contents
	private void onResetContents() {
		TopTabbedView.setSelectedComponent(TopTabbedView.GraphPanel);
		getGraphicView().resetContent();
		getGraphicView().repaintAll();
	}
	
	/**
	 * winchkglnchのローカルバージョンを得る
	 * @return
	 */
	private String getWinchkglnchLocalVersion(){
		if(WinchkglnchVersion==null){
			WinchkglnchVersion = getWinchkglnchLocalVersionInit();
		}
		return WinchkglnchVersion;
	}
	
	/**
	 * winchkglnchのversion Stringを読み込む
	 * @return
	 */
	private String getWinchkglnchLocalVersionInit(){
//		MyDirectory mydir = new MyDirectory();
//		File my = mydir.getDirectory();
//		String pass = my.getAbsolutePath();
		String pass = MyPath;
		
		String locver=new String("1.0.0");
		try {
            FileReader in = new FileReader(pass + File.separator + WinchkglnchIniFile);
            BufferedReader  br = new BufferedReader(in);
            String line;
            while((line = br.readLine()) != null){
            	String[] tok = line.split("=");
            	if(tok.length==2){
            		tok[0] = tok[0].trim();
            		if(tok[0].compareToIgnoreCase("version")==0 ){
            			locver = new String(tok[1].trim());
            		}
            	}
            }
            br.close();
            in.close();
        } catch (IOException e) {
            //
        }		
		return locver;
	}


	/**
	 *  プログラムのアップデート
	 */
	private class upDateThread extends Thread {
		
		private boolean Silent = false;
		private String UpdateMessage=null;
		
		upDateThread(boolean silent){
			Silent = silent;
		}
		/**
		 *   Remote version と Local versionを比較してユーザの意向を尋ねる。
		 * @param filename
		 * @param remver
		 * @param remoteVersionStr
		 * @param locver
		 * @param localVersionStr
		 * @return
		 */
		private boolean doYouUpdate(String filename ,long remver ,String remoteVersionStr,long locver,String localVersionStr){
			String mes;
			String title  = "Checking update " + filename + " ...";
			int icon;
			String selectvalues[] ;
			int defaultselect;
			int abortselect;
			boolean newfile=false;
			if(remver==locver){
				mes = filename + " is the latest version."+ "\nVer" + localVersionStr ;
				icon = JOptionPane.QUESTION_MESSAGE;
				selectvalues = new String[]{"OK - close this dialog","Force update"};
				defaultselect=0;
				abortselect=0;
			}
			else if(remver < locver){
				mes = filename + " is newer version."+ "\nVer" + localVersionStr + "  (remote Ver" + remoteVersionStr + ")";
				icon = JOptionPane.QUESTION_MESSAGE;
				selectvalues = new String[]{"OK - close this dialog","Force update"};
				defaultselect=0;
				abortselect=0;
			}
			else{
				mes = filename + " Found new version\n" + "Version" +localVersionStr + " -> " +remoteVersionStr ;
				icon = JOptionPane.INFORMATION_MESSAGE;
				selectvalues = new String[]{"Cancel","Update now"};
				defaultselect=0;
				abortselect=0;
				newfile = true;
			}
		    if(Silent && !newfile){
		    	return false;
		    }
			int select = JOptionPane.showOptionDialog(null,mes,title,JOptionPane.YES_NO_OPTION,icon,null,selectvalues,selectvalues[defaultselect]);				
			if(select==abortselect){
				return false;
			}
			return true;
		}
		/**
		 * winchkgのversion Stringを返す
		 * @return
		 */
		private String getWinchkgLocalVersion(){
			return Version;
		}
		/**
		 * winchkglnchのversion を返す。
		 * "1.2.3"
		 * @return
		 */
		/**
		 * 読み込まれたリモートのversionファイルからkeyで示されるversionを取得して、localVerと比較しアップデートするかをユーザに尋ねる
		 * もし、updateが指示されたら、passで示されるフォルダにファイルをダウンロードする。
		 * @param ud
		 * @param key
		 * @param localVer
		 * @param pass
		 * @return
		 */
		private boolean checkAndUpdate(String title,RemoteUpdate ud,String key,String localVer,String pass){
			String[] winchkg = null;
			
			winchkg = ud.VersionData.get(key);
			if(winchkg!=null){
				long remver = RemoteUpdate.convVersionStrToValue(winchkg[1]);
				long locver = RemoteUpdate.convVersionStrToValue(localVer);
				
				// winchkg本体のチェック
				if(doYouUpdate(title , remver ,winchkg[1], locver,localVer)){
					if(downLaodFile(pass,winchkg[3],winchkg[2])){
						UpdateMessage=new String( title + "," + localVer + ", "+ winchkg[1] + " , ");
						
						try {
							copyTransfer(pass +  File.separator + winchkg[3],pass +  File.separator + winchkg[2]);
						}
						catch( IOException e){
							
						}
						
						return true;
					}
				}
				
			}
			return false;
		}
		
		/**
		 * コピー元のパス[srcPath]から、コピー先のパス[destPath]へ
		 * ファイルのコピーを行います。
		 * コピー処理にはFileChannel#transferToメソッドを利用します。
		 * 尚、コピー処理終了後、入力・出力のチャネルをクローズします。
		 * @param srcPath    コピー元のパス
		 * @param destPath    コピー先のパス
		 * @throws IOException    何らかの入出力処理例外が発生した場合
		 */
		private  void copyTransfer(String srcPath, String destPath) 
		    throws IOException {
		    
		    FileChannel srcChannel = new
		        FileInputStream(srcPath).getChannel();
		    FileChannel destChannel = new
		        FileOutputStream(destPath).getChannel();
		    try {
		        srcChannel.transferTo(0, srcChannel.size(), destChannel);
		    } finally {
		        srcChannel.close();
		        destChannel.close();
		    }

		}

		
		// 
		/**
		 *  アップデートを行うスレッド
		 */
		public void run(){
			RemoteUpdate ud = new RemoteUpdate();
			if(!ud.getRemoteVersion(RemoteFolder + RemoteVersionFile)){
				//System.err.println("Version control file not found. ");
				return;
			}

			String pass = MyPath;
			
			// winchkgをアップデート
			boolean dirty = false;
			String mes = " ";
			
			// update情報をpostするために
			Date date1  = new Date();
			SimpleDateFormat fmt=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
			fmt.format(date1);
			String loggMessage = fmt.format(date1) + " , ";
			
			if(checkAndUpdate("winchkg",ud,UpdateVersionKey,getWinchkgLocalVersion(),pass)){
				loggMessage += UpdateMessage;
				mes += "\n winchkg "; 
				dirty=true;
			}
			else{
				loggMessage += " , , ,  ";
			}
			// winchkglnchをアップデート
			String locver=getWinchkglnchLocalVersion();
			
			if(checkAndUpdate("winchkglnch",ud,WinchkglnchKey,locver,pass)){
				loggMessage += UpdateMessage;
				mes += "\n winchkglnch "; 
				dirty=true;
			}
			else{
				loggMessage += " , , ,  ";
			}
			if(JavaPropertyMap!=null){
				// ----------------------------------------------------- 
				// OS名　情報
				String os = (String)JavaPropertyMap.get("os.name");
				
				if(os == null){
					os = "cannot get";
				}
				loggMessage += os + ",";
				
				// ----------------------------------------------------- 
				// JAVA バージョン　情報
				String javaver =  (String)JavaPropertyMap.get("java.version");
				if(javaver==null){
					javaver = "cannot get";
				}
				loggMessage += "JAVA " + javaver + "," ;
				// ----------------------------------------------------- 
				// winchkg IDバージョン　情報
				loggMessage += WinchkgID + ",";
				
			}
			
			if(dirty){
				postMessage(loggMessage);
				if(JOptionPane.YES_OPTION != JOptionPane.showConfirmDialog(null,"Success in downloading" + mes + "\n\n" + "Re-launch now ?","Update finished",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE)){
					return;
				}
				reLaunchwinchkg();
			}
			
		}
		/**
		 * サーバーにメッセージをポストする
		 * @param logmessage
		 */
		private void postMessage(String logmessage) {
			URL url;
			try {
				url = new URL(RemotePost);
				HttpURLConnection http = (HttpURLConnection)url.openConnection();
				http.setUseCaches(false);
				http.setRequestMethod("POST");
				http.setDoOutput(true);
	     		
	     		
				OutputStreamWriter osw = new OutputStreamWriter( http.getOutputStream() );

				String outmes  = "sendlog="+logmessage;
				osw.write(outmes);
				osw.close();
				//　読み出さないといけない
				InputStreamReader	ir1 = new InputStreamReader(http.getInputStream());
				BufferedReader	br1 = new BufferedReader(ir1);
				
				//	１行ずつ書き出す
				String line;
				while((line=br1.readLine()) != null)
				{
					//改行がカットされてるので、printlnになる。
					System.out.println(line);
				}
				//	クローズ
				br1.close();
				ir1.close();

				http.disconnect();
				
				
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		
		}
		private String Integer(int length) {
			return null;
		}
	};

	/**
	 *  プログラムのアップデート
	 */
	private boolean downLaodFile(String pass,String locfile,String remfile){
		String name = pass +  File.separator + locfile;
		RemoteUpdate ud = new RemoteUpdate();
		if(!ud.getUrlFile(RemoteFolder + remfile,name)){
			JOptionPane.showMessageDialog(null, "Fail to download file","Download",JOptionPane.ERROR_MESSAGE);
			return false;
		}
		return true;
	}
	/**
	 * winchkgを再起動する。
	 * 成功すると戻らない
	 * 失敗するとfalseを返す
	 * @return
	 */
	private boolean reLaunchwinchkg()
	{
		String pass = MyPath;
		
		String launcher = pass +  File.separator + UpdateLauncher;
		if(OsName ==MyDirectory.OSName.MAC_OSX){
			launcher = UpdateLauncher;
		}
		//ProcessBuilder pb = new ProcessBuilder(new String[] { "java", "-jar",launcher });
		ProcessBuilder pb = new ProcessBuilder(new String[] { "java", "-jar",launcher });
		try {
			pb.start();
			onExit();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "Fail to launch winchkglnch.jar\n","Launch winchkglnch",JOptionPane.ERROR_MESSAGE);
			//e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * WinSenderを起動する。
	 * @return
	 */
	private boolean lunchWinSender()
	{
		String pass = MyPath;
		
		// １つのjarファイルにmainを持つ複数のクラスがある時は、
		// java -classpath aaa.jar class1 で起動できる
		String me = pass +  File.separator + MyJarFile;
		ProcessBuilder pb = new ProcessBuilder(new String[] { "java","-classpath",me ,"WinSender"});
		try {
			pb.start();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "Fail to launch ","Launch winchkg",JOptionPane.ERROR_MESSAGE);
			//e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * ドキュメントを起動。
	 * @return
	 */
	private boolean veiwPDFDoc(String file)
	{
		String pass = MyPath;
		
		
		String me = pass +  File.separator + file;
		
		File f=new File(me);
		try {
			PDFViewAndPrint.openDocument(f);
		} catch (IOException e) {
			System.err.println("Cannot open document\n"+me);
			//e.printStackTrace();
		}	
		
		
		return true;
	}
	/**
	 * 
	 */
	private void onUpdate(boolean silent){
		Thread th = new upDateThread(silent);
		th.setPriority(Thread.MIN_PRIORITY);
		th.start();
		winchkgProperty.UpdateCheckDate = Calendar.getInstance().getTime().getTime();; // 成否にかかわらず...
	}

	//--------------------------------------------------------
	private void onSystemInfo()
	{
		String mes = "winchkg     " + Version + "\n";
		mes       += "winchkglnch " + getWinchkglnchLocalVersion() + "\n\n";
		mes       += helpWindow.getMemoryInfo();
		mes       +="\n"+ "winchkg ID\n" + "       "+WinchkgID;
		
		System.out.println( "\n---System Information ------------------------------\n\n" + mes + "\n---------------------------------\n");
		Iterator itr = JavaPropertyMap.keySet().iterator();
	    while (itr.hasNext()) {
	        String key = (String)itr.next();
	        String value = (String)JavaPropertyMap.get(key);
	        System.out.println(key + "=" + value);
	    }
		mes += "\n\n Additional information is displayed on stdout.\n ";
	    JOptionPane.showConfirmDialog(this, mes,"System information", JOptionPane.CLOSED_OPTION, JOptionPane.INFORMATION_MESSAGE);
	}
	
	
	private helpWindow HelpWindow = null;
	/**
	 * ヘルプのとき
	 */
	private void onHelp()
	{
		HelpWindow = new helpWindow();
		HelpWindow.setSize(600, 800);
		//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//		HelpWindow.setAlwaysOnTop(true);
		// TODO パッケージの位置に依存する部分
		HelpWindow.showHelp("/help_en.txt");
		HelpWindow.setVisible(true);
	}
	private void onHelpJ()
	{
		HelpWindow = new helpWindow();
		HelpWindow.setSize(600, 800);
		//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//HelpWindow.setAlwaysOnTop(true);
		// TODO パッケージの位置に依存する部分
		HelpWindow.showHelp("/help.txt");
		HelpWindow.setVisible(true);
		//HelpWindow.showHelp("/winchkghelp.html");
	}
	//--------------------------------------------------------
	/*
	 * when pushed the buttons 
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent ev){
		if( ev.getActionCommand() == "start"){
			//		  TopTabbedView.ResetContent();
			//		  actionperformedStart();
		}
		else if(ev.getActionCommand()=="option"){
			onOption();
		}
		else if(ev.getActionCommand()=="SystemOptions"){
			onSystemOptions();
		}
		else if(ev.getActionCommand()=="Open"){
			TopTabbedView.setSelectedComponent(TopTabbedView.GraphPanel);

			// 複数ファイルの選択とディレクトリの選択が可能
			JFileChooser filechooser = new JFileChooser(currentFileOpenDirectory);
			filechooser.setDialogTitle("Open win files / directory");
			filechooser.setMultiSelectionEnabled(true);
			filechooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
			int selected = filechooser.showOpenDialog(this);
			if ( selected == JFileChooser.APPROVE_OPTION ) {
				File[] file = filechooser.getSelectedFiles();
				TreeSet<String> st = TopTabbedView.DataBase.Dir2Files(file);
				TopTabbedView.GraphPanel.getGraphicView().openFiles(st);
				TopTabbedView.DataBase.addHistory(st); // ヒストリにいれる。
				currentFileOpenDirectory = filechooser.getCurrentDirectory().getPath();
			}
		}
		
		else if(ev.getActionCommand()=="OpenRecentFiles"){
			onOpenRecentFile();
		}
		else if(ev.getActionCommand()=="Save folder"){
			String initPath = new String(".");
			if(WinUdp2File!=null) initPath = WinUdp2File.getPath();
			JFileChooser filechooser = new JFileChooser(initPath);
			filechooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );	      
			filechooser.setDialogTitle("Save folder");
			int selected = filechooser.showSaveDialog(this);
			if ( selected == JFileChooser.APPROVE_OPTION ) {
				File file = filechooser.getSelectedFile ();
				String dirPath = file.getAbsolutePath();
				TopTabbedView.DataBase.setWriteOutFolder(dirPath);
			}
		}
		else if(ev.getActionCommand()=="Option"){
			onOption();
		}
		else if(ev.getActionCommand()=="Exit"){
			onExit();
		}
		else if(ev.getActionCommand()=="Help(en)"){
			onHelp();
		}
		else if(ev.getActionCommand()=="Help(jp)"){
			onHelpJ();
		}
		else if(ev.getActionCommand()=="Systeminfo"){
			onSystemInfo();
		}
		else if(ev.getActionCommand()=="Update"){
			onUpdate(false);
		}
		else if(ev.getActionCommand()=="Reset Contents"){
			onResetContents();
		}
		else if(ev.getActionCommand()=="ViewChannelIni"){
			TopTabbedView.setSelectedComponent(TopTabbedView.GraphPanel);
			getGraphicView().selectDisplayChannel(1);
		}
		
		else if(ev.getActionCommand()=="ImportCSV"){
			onImportCSV();
			//getGraphicView().ImportCSV();
		}
		else if(ev.getSource() == getCsvImportDlg().ButtonImport){
			doImportCSV();
		}
		else if(ev.getActionCommand()== "Debug command console"){
			console.setVisible(true);
		}
		else if(ev.getActionCommand()== "IrigTools"){
			if(DlgIrigInfo == null){
				DlgIrigInfo = new DialogIrigInfo(null);
			}
			
			wintime wt = new wintime(TopTabbedView.DataBase.DispStartTimeSec);
			wintime wt2 = new wintime(wt.year(),wt.month(),wt.day(),wt.hour(),wt.min(),0);
			if(wt.msec()!=0){
				wt2.inc_sec();
			}
			if(wt.sec()!=0){
				wt2.inc_min();
			}
			String str = wt2.fmt();
			DlgIrigInfo.setTime(str);
			DlgIrigInfo.setVisible(true);
		}
		else if(ev.getActionCommand()== "ReceiveUDP"){
			onReveiveUDPCommand();
		}
		
	}
	/**
	 * CSVのインポート
	 */
	private void onImportCSV() {
		ImportCSV();
		
	}
	private CsvImportDlg CSVimport = null;
	private CsvImportDlg getCsvImportDlg(){
		if(CSVimport == null){
			CSVimport = new CsvImportDlg();
			CSVimport.Parent=this;
			CSVimport.LoadConfFile("csvconf.ini");
			CSVimport.SetOutDir("csvimp.win");
		}
		return CSVimport;
	}
	private void ImportCSV() {
		CsvImportDlg dlg =  getCsvImportDlg();
		CSVimport.LoadConfFile("csvconf.ini");
		dlg.setVisible(true);
	}
	private void doImportCSV(){
		String dt = CSVimport.getImportDataAsFile();
		if(dt == null) return;
		if(JOptionPane.YES_OPTION== JOptionPane.showConfirmDialog(this, String.format("Create win file\n  %s\n Display now ?" , dt),"CSV File import",JOptionPane.YES_NO_OPTION)){
			TopTabbedView.DataBase.addChData(dt);
			
		}
		
	}

	/**
	 * Recent Fileを表示して再び開く
	 */
	private void onOpenRecentFile(){
		

		int n = TopTabbedView.DataBase.getHistoryNumber();
		
		DlgSelectRecentFile dlg = new DlgSelectRecentFile();

		LinkedList<String> lst = new LinkedList<String>();
		LinkedList<Integer> indexList = new LinkedList<Integer>();
		for(int i=0;i<n;i++){
			// 逆順に挿入
			String s = TopTabbedView.DataBase.getHistoryName(n-i-1);
			if(s!=null){
				if(!isContains(lst,s)){
					dlg.addData(s);
					indexList.add(n-i-1);	// 	ダイアログ内の順番とヒストリの順番を保存
				}
				lst.add(s);
			}
		}
		dlg.setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
		// モーダルダイアログを開いて
		dlg.setLocation(getLocationOnScreen().x+20,getLocationOnScreen().y+20);
		dlg.setVisible(true);
		
		if(dlg.Ok){
			TopTabbedView.setSelectedComponent(TopTabbedView.GraphPanel);
			// ファイルを開く
			int[] indx = dlg.getIndeces();
			for(int i=0;i<indx.length;i++){
				int dx = indx[i];
				dx = indexList.get(dx);
				TreeSet<String> ts = TopTabbedView.DataBase.getHistory(dx);
				TopTabbedView.DataBase.addChDataTh(ts);
			}
		}
		return ;
	}
	/**
	 * ストリングリストの中に同じ文字列が含まれるかどうか
	 * @param lst
	 * @param s
	 * @return
	 */
	private boolean isContains(LinkedList<String> lst,String s){
		for(int i=0;i<lst.size();i++){
			if(s.compareToIgnoreCase(lst.get(i))==0){
				return true;
			}
		}
		return false;
	}
	//---------------------------------------
	private void onReveiveUDPCommand(){
		DlgReceiveUDPSetting dlg = new DlgReceiveUDPSetting();
		dlg.setPort(Port);
		if(RxEnable) 		dlg.setRecvUdp(true);
		else				dlg.setRecvUdp(false);
		dlg.doDataExchange(false);
		dlg.setModalityType(Dialog.ModalityType.DOCUMENT_MODAL );
		dlg.setLocationRelativeTo(this);
		dlg.setVisible(true);
		if(dlg.ReturnCode){
			dlg.doDataExchange(true);
			onSetPort( dlg.getPort());
			if(dlg.isRecvUdp()){
				onRecieveUDP(true);
			}
			else{
				onRecieveUDP(false);
			}
		}
	}
	//--------------------------------------------------------
	private void onOption() {
		winchkOption opt = new winchkOption(this);
		opt.DisplayLevel = DisplayLevel;
		opt.setValue();
		opt.setModal(true);
		opt.setVisible(true);
		if(opt.Ok){
			DisplayLevel = opt.DisplayLevel;
			TopTabbedView.Checker.setDisplayLevel(DisplayLevel);
			TopTabbedView.Checker.setCheckInterFiles(!opt.NotCheckInterFiles);
		}
	}
	//--------------------------------------------------------
	class cTimer extends TimerTask{
		public void run(){
			timerRoutine();
		}
	}
	//--------------------------------------------------------
	private  void timerRoutine() {
		if(UdpList == null) return;
		while (true) {
			byte[] dat ;
			synchronized (UdpList){
				if (UdpList.isEmpty()) {
					break;
				}
				dat = UdpList.removeFirst();
			}
			if (RxEnable){
				getGraphicView().addUdpChData(dat);
				Durty++;
			}

			if (FileWriteEnable != 0){
				WinUdp2File.add(dat);
			}
		}
		int paintTime =(int)( (getGraphicView().getPaintTime()+100)/100);
		if(++DispCounter>(int)paintTime){
			if(Durty != 0) {
				Durty = 0;
				DispCounter=0;
				getGraphicView().UdpRetryCounter = RetryCounter;
				getGraphicView().UdpRetryRecvCounter = RetryRecvCounter;
				getGraphicView().repaintAll();
			}
		}
	}
	//--------------------------------------------------------
	@Override
	public void onRecieve(DatagramPacket pac) {
		synchronized (UdpList){
			int len = pac.getLength();
			byte[] dat = new byte[len];
			System.arraycopy(pac.getData(), 0, dat, 0, len);
			UdpList.add(dat);
		}
		
		if(RetryCounter != WinServer.monitor.winA0UdpSendRetryCounter){
			RetryCounter = WinServer.monitor.winA0UdpSendRetryCounter;
			RetryRecvCounter = WinServer.monitor.winA0UdpRetryPacketRecvCounter;
		}

	}
	//--------------------------------------------------------
	@Override
	public void onError(DatagramPacket pac, int error) {
		String mes = new String();
		mes = String.format("winchkg Packet error %d", error);
		System.err.println(mes);
	}
	//--------------------------------------------------------
	@Override
	public void onTimeout() {
		//System.out.println("packet timeout");
	}
	//--------------------------------------------------------
	private GraphicView getGraphicView(){
		return TopTabbedView.GraphPanel.getGraphicView();
	}
	//--------------------------------------------------------
	private SpectrumView getSpectrumView(){
		if(TopTabbedView.SpectrumPanel!=null){
			return TopTabbedView.SpectrumPanel.getSpectrumView();
		}
		return null;
	}
	private DynamicRangeView getSNRView(){
		if(TopTabbedView.SNRChartPanel!=null){
			return TopTabbedView.SNRChartPanel.getJPanelSNRView();
		}
		return null;
	}
	//--------------------------------------------------------
	private GraphicViewPanel getGraphicViewPanel(){
		return TopTabbedView.GraphPanel;
	}
	//--------------------------------------------------------
	/**
	 * UDP受信するかどうか
	 * @param recv
	 */
	private void onRecieveUDP(boolean recvEnable){
		if(recvEnable == RxEnable ) return;
		if(recvEnable){
			try{
				//Port = Integer.valueOf(getGraphicViewPanel().jTextFieldPort.getText());
			} catch(NumberFormatException e){
				Port=7200;
				return;
			}
			//getGraphicViewPanel().jTextFieldPort.setEnabled(false);
			startWinA0Server();
			if(RxEnable){
				//TopTabbedView.Graph.resetContent();
			}
			RxEnable = true;
			getGraphicViewPanel().jCheckBoxRcvUdp.setSelected(RxEnable);
		}
		else{
			//getGraphicViewPanel().jTextFieldPort.setEnabled(true);
			RxEnable = false;
			stopWinA0Server();
			WinUdp2File.writeFile(true); // flush
			getGraphicViewPanel().jCheckBoxRcvUdp.setSelected(RxEnable);
		}
	}
	private void onSetPort(int port){
		if(port == Port) return;
		Port = port;
		getGraphicViewPanel().jTextFieldPort.setText(String.valueOf(Port));
		
	}
	/**
	 * ファイルに書き込むかどうか
	 * @param writeEnable
	 */
	private void onFileWrite(boolean writeEnable){
		if(writeEnable) {
			FileWriteEnable = 1;
		}
		else{
			FileWriteEnable = 0;
			WinUdp2File.writeFile(true); // flush
		}
	}
	
	@Override
	public void itemStateChanged(ItemEvent arg0) {
		int kkk=0;
		if(arg0.getSource().equals(getGraphicViewPanel().jCheckBoxRcvUdp)){
			int port=7200;
			try{
				port = Integer.valueOf(getGraphicViewPanel().jTextFieldPort.getText());
				
			} catch(NumberFormatException e){
			}
			onSetPort(port);
			boolean recvenable = getGraphicViewPanel().jCheckBoxRcvUdp.isSelected();
			onRecieveUDP(recvenable);
		}
		else if(arg0.getSource().equals(getGraphicViewPanel().jCheckBoxWriteFile)){
			boolean writeEnable = getGraphicViewPanel().jCheckBoxWriteFile.isSelected();
			onFileWrite(writeEnable);
		}
		else if(arg0.getSource().equals(getGraphicViewPanel().jCheckBoxAutoDisplay)){
		}
		
		else if(arg0.getSource()== DisableSendAck){
			boolean b = DisableSendAck.getState();	
			if(WinServer!=null){
				WinServer.ACTAckEnable = !b;
			}
		}
	}
	//--------------------------------------------------------
	@Override
	public void stateChanged(ChangeEvent e) {
	}
	
	public void printHelp(int level){
		console.print("\n*\n*\n Winchkg class Debug Command summary \n*\n*\n");
		if(level >= 0x100){
			console.print(" edition set [basic/users]\n");
			console.print(" reset:\n    reboot program\n");
			console.print(" monitor protocol sequence_error :\n    show winA0/ACT protocol sequence error on stdout\n");
			console.print(" monitor protocol error  :\n    show winA0/ACT protocol error on stdout\n");
			console.print(" monitor protocol ack_nack :\n    show winA0/ACT protocol ack(ACT)/nack(winA0)on stdout\n");
			console.print(" monitor protocol all :\n    show winA0/ACT protocol all on stdout\n");
			console.print(" monitor protocol off : \n");
			console.print(" display protocol status :\n    show winA0/ACT protocol status\n");
			console.print(" exception test :\n    Generate exception for test\n");
			console.print(" update beta yes/no :\n    download beta version or not\n");
			console.print(" launch winsender :\n    launch test program winsender sending winA0/ACT packet\n");
			console.print(" print whiteback yes/no :\n    print always white background or not\n");
			console.print(" changeCHID oldCH newCH :\n    Change channel ID  odlCH to newCH");
			console.print(" changeCHID offset :\n    Change all channel ID  CH=CH+offset");
		}
		//console.print(" edition set [elementary/basic/users/superusers]\n");
		console.print(" reset:\n    reboot program\n");
	}
	// Debug command interface
	@Override
	public void OnCommand(String cmd) {
		
		String[] cm = Optionconsole.getCommand(cmd);
		if(cm==null) return;

		Date date1=new Date();
		DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
		//System.out.println(df.format(date1));
		console.print("\n>"+df.format(date1)+"\n");

		for(int i=0;i<cm.length;i++){
			console.print(cm[i] + " ");
		}
		console.print("\n");
		
		if(0==cm[0].compareTo("help")){
			printHelp(winchkgProperty.EditionControl);
		}
		/// ＧＯＤモードヘルプ
		else if(0==cm[0].compareTo("???")){
			printHelp(0x7fffffff);
			console.print(" edition set [basic/users/superusers/developers/god]\n");
			console.print(" ts/[time chart command]  : ts/help\n");
		}
		
		else if(0==cm[0].compareTo("launch")){
			if(cm.length>=2){
				if(0==cm[1].compareTo("winsender")){
					lunchWinSender();
				}
			}
		}
		else if(0==cm[0].compareTo("test")){
			veiwPDFDoc("helpj.pdf");
		}
		else if(0==cm[0].compareTo("update")){
			if(cm.length<2){
				return;
			}
			if(0==cm[1].compareTo("beta")){
				if(cm.length>=3){
					if(cm[2].compareToIgnoreCase("no")==0){
						winchkgProperty.UpdateBeta = false;
						UpdateVersionKey = UpdateDistribeVersionKey;
					}
					if(cm[2].compareToIgnoreCase("yes")==0){
						winchkgProperty.UpdateBeta = true;
						UpdateVersionKey = UpdateBetaVersionKey;
					}
				}
				if(winchkgProperty.UpdateBeta){
					console.print("beta = yes\n");
				}
				else{
					console.print("beta = no\n");
				}
				console.print(UpdateVersionKey);
			}
			
		}
		else if(0==cm[0].compareTo("print")){
			if(cm.length<2){
				return;
			}
			if(0==cm[1].compareTo("whiteback")){
				if(cm.length>=3){
					if(cm[2].compareToIgnoreCase("no")==0){
						winchkgProperty.PrintColorAlwaysWhite = false;
					}
					if(cm[2].compareToIgnoreCase("yes")==0){
						winchkgProperty.PrintColorAlwaysWhite = true;
					}
				}
				if(winchkgProperty.PrintColorAlwaysWhite){
					console.print("white back = yes");
				}
				else{
					console.print("white back = no");
				}
			}
		}
		else if(0==cm[0].compareTo("edition")){
			if(cm.length<2){
				String ed = winchkgProperty.getEditionNames();
				if(ed !=null) {
					console.print("Current Edition = " + ed + "\n");
				}
				else{
					console.print(String.format("Current Edition = %d\n",winchkgProperty.EditionControl));
					
				}
				return;
			}
			if(0==cm[1].compareTo("set")){
				if(cm.length<3) return;
				try{
					int edition = Integer.parseInt(cm[2]);
					if(edition >= 0 && edition<=0x7fffffff){
						winchkgProperty.EditionControl = edition;
						console.print(String.format("Set edition = %d\nPlease re-launch",edition));
					}
				}catch(NumberFormatException e){
					boolean ok = false;
					if(cm[2].compareToIgnoreCase("basic") == 0)	{
						winchkgProperty.setEditionControl("basic");
						ok = true;
					}
					else if(cm[2].compareToIgnoreCase("users") == 0)	{
						winchkgProperty.setEditionControl("users");
						ok = true;
					}
					else if(cm[2].compareToIgnoreCase("superusers") == 0)	{
						winchkgProperty.setEditionControl("superusers");
						ok = true;
					}
					else if(cm[2].compareToIgnoreCase("developers") == 0)	{
						winchkgProperty.setEditionControl("developers");
						ok = true;
					}
					else if(cm[2].compareToIgnoreCase("god") == 0)	{
						winchkgProperty.setEditionControl("god");
						ok = true;
					}
					if(ok){
						console.print(String.format("Set edition = %s\nPlease re-launch",cm[2]));
					}
				}
			}

		}
		else if(0==cm[0].compareTo("monitor")){
			if(cm.length<2) return;
			if(0==cm[1].compareTo("protocol")){
				if(cm.length<3) return;
				if(0==cm[2].compareTo("sequence_error")){
					if(WinServer!=null){
						WinServer.printMessageControl |= WinReceiver.showSeqError;
						console.print(String.format("set showSeqError (%x)",WinServer.printMessageControl));
					}
				}
				else if(0==cm[2].compareTo("error")){
					if(WinServer!=null){
						WinServer.printMessageControl |= WinReceiver.showProtocolError;
						console.print(String.format("set showProtocolError (%x)",WinServer.printMessageControl));
					}
				}
				else if(0==cm[2].compareTo("ack_nack")){
					if(WinServer!=null){
						WinServer.printMessageControl |= WinReceiver.showAckOrNack;
						console.print(String.format("set showAckOrNack (%x)",WinServer.printMessageControl));
					}
				}
				else if(0==cm[2].compareTo("all")){
					if(WinServer!=null){
						WinServer.printMessageControl |= (WinReceiver.showAckOrNack|WinReceiver.showProtocolError|WinReceiver.showSeqError);
						console.print(String.format("set all (%x)",WinServer.printMessageControl));
					}
				}
				else if(0==cm[2].compareTo("off")){
					if(WinServer!=null){
						WinServer.printMessageControl =0;
						console.print(String.format("set off (%x)",WinServer.printMessageControl));
					}
				}
		
			}
		}
		else if(0==cm[0].compareTo("display")){
			if(cm.length<2) return;
			if(0==cm[1].compareTo("protocol")){
				if(cm.length<3) return;
				if(0==cm[2].compareTo("status")){
					if(WinServer!=null) {
						String mes = WinServer.getStatusString();
						console.print(mes);
					}
				}
			}
		}
		else if(0==cm[0].compareTo("exception")){
			if(0==cm[1].compareTo("test")){
				cm[100] = "test";
			}
		}
		else if(0==cm[0].compareTo("reset")){
			reLaunchwinchkg();
		}
		else if(0==cm[0].compareTo("re-launch")){
			reLaunchwinchkg();
		}
		else if(0==cm[0].compareTo("changeCHID")){
			if(cm.length<2) {
				console.print("changeCHID oldCH newCH or changeCHID offset");
				return;
			}
			try{
				if(cm.length==2) {
					int id1 = Integer.parseInt(cm[1],16);
					changeChannelID(id1);
				}
				else{
					int id1 = Integer.parseInt(cm[1],16);
					int id2 = Integer.parseInt(cm[2],16);;
					changeChannelID(id1,id2);
				}
			}catch(NumberFormatException e){
				console.print("number format error!");
			}
			
		}
		else{
			console.print("command not found");
		}
	}
	/**
	 * Channel ID を変更する
	 * @param id1　変更前のＩＤ
	 * @param id2　変更後のＩＤ
	 */
	private void changeChannelID(int id1, int id2) {
		TopTabbedView.DataBase.changeChannelID(id1,id2);
	}
	/**
	 * Channel ID を変更する
	 * @param id1　変更前のＩＤ
	 * @param id2　変更後のＩＤ
	 */
	private void changeChannelID(int offset) {
		TopTabbedView.DataBase.changeChannelID(offset);
	}
	@Override
	public void menuCanceled(MenuEvent arg0) {
		
	}
	@Override
	public void menuDeselected(MenuEvent arg0) {
		
	}
	// メニューを開いたときのイベント
	@Override
	public void menuSelected(MenuEvent arg0) {
		JMenu menu = (JMenu)arg0.getSource();
		String cmd = menu.getActionCommand();
		if(cmd.compareToIgnoreCase("VIEW")==0){
		}
		else if(cmd.compareToIgnoreCase("DATA")==0){
			if(WinServer!=null){
				if(DisableSendAck != null){
					DisableSendAck.setSelected(WinServer.ACTAckEnable);
				}
			}
		}
	}
}
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
class PanelTopView extends JTabbedPane implements DropTargetListener , TextListener{
	private static final long serialVersionUID = 1L;
//	private OutputTextArea Out;
//	private OutputTextArea Err;
	public CheckerView Checker;
	public GraphicViewPanel GraphPanel=null;
	public SpectrumViewPanel SpectrumPanel = null;
	public winDataBase DataBase = new winDataBase(); // これがデータ
	public DynamicRangePanel SNRChartPanel = null;
	public SignalProcessingPanel SignalProcessing;
	//--------------------------------------------------------
	public PanelTopView(){
		super();
		GraphPanel = new GraphicViewPanel();
		GraphPanel.jCheckBoxAutoDisplay.setSelected(true);
		GraphPanel.getGraphicView().setwinDataBase(DataBase);
		GraphPanel.setWinDataBase(DataBase);
		DataBase.DataSetter=GraphPanel.getGraphicView();
		int tabnumber = 0;
		//this.add("Time-Chart",GraphPanel);
		this.insertTab("Time series",
				new ImageIcon(getClass().getClassLoader().getResource("images/wave3.png"))
				,GraphPanel,"View wave form ",tabnumber++);
		
		if(winchkgProperty.availableSpectrumPane){
			SpectrumPanel = new SpectrumViewPanel();
			SpectrumPanel.setwinDataBase(DataBase);
			//this.add("Spectrum",SpectrumPanel);
			this.insertTab("Spectrum",
					new ImageIcon(getClass().getClassLoader().getResource("images/spectrum1.png"))
					, SpectrumPanel, "Spectrum view", tabnumber++);
				
		}
		if(winchkgProperty.availableDynamicRangePane){
			SNRChartPanel = new DynamicRangePanel();
			SNRChartPanel.setwinDataBase(DataBase);
			//this.add("SNR",SNRChart);
			this.insertTab("DynamicRange",
					new ImageIcon(getClass().getClassLoader().getResource("images/snr3.png"))
					,SNRChartPanel,"Running DynamicRange ratio",tabnumber++);
		}
		//if(winchkgPropInst.EditionControl == winchkgPropInst.EditionControlFull){
			Checker = new CheckerView();
			Checker.setParent(this);
			this.insertTab("Misc tools/stdout/stderr",
					new ImageIcon(getClass().getClassLoader().getResource("images/wrench_orange.png"))
					,Checker,"Miscellaneous tools, std out and std err",tabnumber++);
		//}
//		this.insertTab(" ",
//				new ImageIcon(getClass().getClassLoader().getResource("images/datamark_bar_21.png"))
//				,null,"http://www.hakusan.co.jp",tabnumber++);

			if(winchkgProperty.availableSignalProcessingPane){
				// TODO: SignalProcessing　を作成中
				SignalProcessing = new SignalProcessingPanel();
				SignalProcessing.setwinDataBase(DataBase);
				//this.add("SNR",SNRChart);
				this.insertTab("SignalProcessing",
						new ImageIcon(getClass().getClassLoader().getResource("images/calculator.png"))
						,SignalProcessing,"Signal Processing",tabnumber++);
			}
		new DropTarget(this,this);
	}
	public void onTabChanged() {
		GraphPanel.getGraphicView().onTabChanged();
		
	}
	//--------------------------------------------------------
	public void ResetContent(){
		if(Checker != null){
			Checker.ResetContents();
		}
	}
	public void AddFiles(String[] arg){
		TreeSet<String> ts = DataBase.Dir2Files(arg);
		if(ts==null) return;
		DataBase.addChData(ts);
	}
	@Override
	public void dragEnter(DropTargetDragEvent arg0) {
	}
	@Override
	public void dragExit(DropTargetEvent arg0) {
	}
	@Override
	public void dragOver(DropTargetDragEvent arg0) {
	}
	@Override
	public void drop(DropTargetDropEvent arg0) {
		this.setSelectedComponent(GraphPanel);
		GraphPanel.getGraphicView().drop(arg0);
	}
	@Override
	public void dropActionChanged(DropTargetDragEvent arg0) {
	}
	private int Counter=0;
	@Override
	public void textValueChanged(TextEvent e) {
		// std errに変更があった場合
		Object obj = e.getSource();
		if(obj instanceof OutputTextArea){
			//this.setSelectedIndex(3);
			this.setSelectedComponent(Checker);
			OutputTextArea ta = (OutputTextArea)obj;//@
			String str = ta.getText();
		}
		
	}

}

//--------------------------------------------------------

